package icu.zhhll.excel.handler;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.WorkbookWriteHandler;
import com.alibaba.excel.write.handler.context.WorkbookWriteHandlerContext;
import icu.zhhll.excel.util.ExcelUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;

import java.util.List;
import java.util.Map;

/**
 * 设置下拉框
 * <p>
 * <code>
 * Map<String,List<String>> fieldDataMap = new HashMap<>();
 * fieldDataMap.put("locationName",locations);
 * <p>
 * EasyExcel.write(new File(fileName), ExcelTemplateData.class).sheet(0)
 * .registerWriteHandler(new ValidationWriteHandler(fieldDataMap))
 * .doWrite(dataList);
 * </code>
 * <p/>
 *
 * @author zh
 * @date 2023/8/20 16:15
 */
public class ValidationWriteHandler implements WorkbookWriteHandler {
    // 该列下拉框对应内容
    private Map<String, List<String>> fieldDataMap;

    public ValidationWriteHandler(Map<String, List<String>> fieldDataMap) {
        this.fieldDataMap = fieldDataMap;
    }

    public ValidationWriteHandler() {

    }


    @Override
    public void afterWorkbookDispose(WorkbookWriteHandlerContext context) {
        Sheet sheet = context.getWriteContext().writeSheetHolder().getSheet();
        Map<Integer, Head> headMap = context.getWriteContext().currentWriteHolder().excelWriteHeadProperty().getHeadMap();

        int lastRowNum = sheet.getLastRowNum();
        if (fieldDataMap != null && fieldDataMap.size() > 0) { // 存在数据，进行下拉框配置
            int count = 1;
            for (Map.Entry<String, List<String>> fieldEntry : fieldDataMap.entrySet()) {
                for (Map.Entry<Integer, Head> headEntry : headMap.entrySet()) {
                    if (StringUtils.equals(headEntry.getValue().getFieldName(), fieldEntry.getKey())) {
                        ExcelUtils.setValidation(lastRowNum, fieldEntry.getValue(), sheet, headEntry.getKey(),
                                fieldEntry.getKey(), count);
                        break;
                    }
                }
                count++;
            }
        }

    }

}
